package com.geekgo.lucenepp.util;

import com.geekgo.lucenepp.model.Field;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * XML工具
 *
 * @author HeHaoyang
 * @create 2017-06-13 17:42
 **/
public final class XMLUtil {

    public static List<Field> xmlTOObj(String xml_Url){
        List<Field> fields = new ArrayList<>();
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(new File(xml_Url));
            List<Element> elements = read.getRootElement().elements();
            elements.forEach(e ->{
                Field field = new Field();
                field.setName(e.attributeValue("name"));
                field.setType(e.attributeValue("type"));
                String isQuery = e.attributeValue("isQuery");
                String isSort = e.attributeValue("isSort");
                String boost = e.attributeValue("boost");
                field.setQuery(false);
                if(StringUtils.isNotBlank(isQuery)){
                    isQuery = isQuery.toLowerCase();
                    if(isQuery.equals("y")){
                        field.setQuery(true);
                    }
                }
                field.setSort("false");
                if(StringUtils.isNotBlank(isSort)){
                    isSort = isSort.toLowerCase();
                    //降序
                    if(isSort.equals("desc")){
                        field.setSort("true");
                    }
                }
                if(StringUtils.isNotBlank(boost)){
                    field.setBoost(Float.valueOf(boost));
                }
                fields.add(field);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }
}
